/* The link = http://poj.org/problem?id=3980
 * Another explanation
 */

#include <iostream>
#include <math.h>

using namespace std;

// @param a, b: Input
// @param q, r: Output
void myMod(int a, int b, int &q, int &r)
{
	if (b == 1)
	{
		q = a; 
		r = 0;
		return;
	}
	myMod(a, b / 2, q, r);

	if (b % 2 == 0) {
		if (q % 2 == 0) {
			q /= 2;
		} else {
			q /= 2;
			r += b /2;
		}
	} else {
		if (q % 2 == 0) {
			r = r - q / 2;
			q /= 2;
		} else {
			r = r + (b - q) / 2;
			q /= 2;
		}
	}
}

int main(int argc, char*argv[])
{
	int a, b;
	while (cin >> a >> b)
	{
		int q, r;
		myMod(a, b, q, r);
		while (r < 0)
			r += b;
		cout << r << endl;
	}
	return 0;
}